#pragma once
#include<iostream>
#include<string>
#include<sys/socket.h>
#include<sys/types.h>
#include<assert.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>


class Socket{
    private:
    const static int gbacklog = 10;
    public:
    static int Sock()
    {
        int listensock = socket(AF_INET,SOCK_STREAM,0);
        if(listensock < 0)
        {
            exit(1);
        }
        int opt = 1;
        setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR | SO_REUSEPORT,&opt,sizeof(opt));
        return listensock;
    }
    static void Bind(int listensock,uint16_t port,std::string ip = "0.0.0.0")
    {
        struct sockaddr_in addr;
        memset(&addr,0,sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        inet_pton(AF_INET,ip.c_str(),&addr.sin_addr);
        if(bind(listensock,(sockaddr*)&addr,sizeof(addr)) < 0)
        {
            exit(2);
        }
    }
    static void Listen(int sock)
    {
        if(listen(sock,gbacklog) < 0)
        {
            exit(3);
        }
    }
    //输入输出函数
    static int Accept(int listensock,std::string* ip,uint16_t* port,int* accept_errno)
    {
        sockaddr_in addr;
        socklen_t len = sizeof(addr);
        int sock = accept(listensock,(sockaddr*)&addr,&len);
        if(sock < 0)
        {
            *accept_errno = errno;
            return -1;
        }
        if(port)
        *port = ntohs(addr.sin_port);
        if(ip)
        *ip = inet_ntoa(addr.sin_addr);
        return sock;
    }
    static bool Connect(int sock,std::string& server_ip,uint16_t& server_port)
    {
        sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(server_port);
        addr.sin_addr.s_addr = inet_addr(server_ip.c_str());
        if(connect(sock,(sockaddr*)&addr,sizeof(addr)) < 0)
        {
            return false;
        }
        return true;
    }
    static bool SetNoBlock(int sock)
    {
        int f1 = fcntl(sock,F_GETFL);
        if(f1 < 0)return false;
        fcntl(sock,F_SETFL,f1 | O_NONBLOCK);
        return true;
    }
};